import React from 'react';
import Header from './components/header';
import pages from './pages';
import './styles/base.scss';
import './styles/code.scss';
import './styles/icons.scss';
import Markdown from './libs/markdown';


export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      page: document.location.hash.split('/')[1] || 'buttons'
    };
  }

  componentWillMount() {
    window.addEventListener("hashchange", () => {
      window.scrollTo(0, 0);

      this.setPage();
    }, false);
  }

  getPage() {
    const routes = location.hash.match(/(?:\/(.+))?\/(.+)/);
    return routes[2];
  }

  setPage(fn) {
    this.setState({ page: this.getPage() }, fn);
  }

  getComponent(page) {
    // this.components = this.components || Object.assign(Object.values(pages).reduce((a, b) => {
    //   return Object.assign(a, b);
    // }, {}));
    const result = pages[page];
    if (result) {
      const Doc = class extends Markdown {
        document() {
          return result.document;
        }
      }
      return React.createElement(Doc, {});
    }
  }

  render() {
    return (
      <div>
        <Header />
        <div className="warpper-container">
          <div className="menu-container">
            <ul>
              {
                Object.keys(pages).map(page => {
                  return (
                    <li key={page} className={`menu-item ${page === this.state.page ? 'active' : ''}`}>
                      <a href={`#/${page}`}>{pages[page].title}</a>
                    </li>
                  )
                })
              }
            </ul>
          </div>
          <div className="main-container">
            { this.getComponent(this.state.page) }
          </div>
        </div>
      </div>
    )
  }
}
